<script setup>
	import { onLoad } from '@dcloudio/uni-app'
	import { ref } from 'vue'
	import { parseTime, getFileType } from '@/utils/common'
	import { getTaskList, arrangeTask, startTask, confirmTask } from '@/api/delivery'
	import { uploadFile } from '@/api/login'
	
	const loading = ref(false)
	const loadStatus = ref('loadmore')
	const navList = ref([{name: '待整理'}, {name: '待配送'}, {name: '配送中'}, {name: '已完成'}])
	const query = ref({status: 0, current: 1, size: 20})
	const triggered = ref(false)
	const total = ref(0)
	const list = ref([])
	const selectStartList = ref([])
	const selectConfirmList = ref('')
	
	const arrangePopup = ref(null)
	const arrangeUForm = ref(null)
	const arrangeForm = ref({
		shippingId: '',
		deliveryCode: ''
	})
	const arrangeRules = ref({
		deliveryCode: [
			{required: true, message: '请输入提货验证码', trigger: 'blur'}
		]
	})
	const arrivePopup = ref(null)
	const uForm = ref(null)
	const form = ref({
		shippingId: '',
		list: [],
		deliveryCode: ''
	})
	const rules = ref({
		list: [
			{type: 'array', required: true, message: '请上传送达照片', trigger: 'change'}
		],
		deliveryCode: [
			{required: true, message: '请输入用户验证码', trigger: 'blur'}
		]
	})
	
	function navChange(e) {
		let index = e.index
		if(query.value.status !== index) {
			query.value.status = index
			triggered.value = true
		}
	}
	function refreshList() {
		if(loadStatus.value === 'loading') return
		loadStatus.value = 'loading'
		triggered.value = true
		list.value = []
		query.value.current = 1
		getTaskList(query.value).then(res => {
			let result = res.result || {}
			let data = result.records || []
			data.forEach(item => {item.num = 0})
			total.value = Number(result.total)
			list.value = data
			triggered.value = false
			let curLength = list.value.length || 0
			loadStatus.value = curLength === total.value? 'nomore' : 'loadmore'
		}).catch(() => {
			triggered.value = false
			loadStatus.value = 'loadmore'
		})
	}
	function lowerList(noReplace = true) {
		if(list.value.length < total.value || !noReplace) {
			loadStatus.value = 'loading'
			query.value.current ++
			getTaskList(query.value).then(res => {
				let result = res.result || {}
				let data = result.records || []
				data.forEach(item => item.expand = false)
				total.value = Number(result.total)
				if(noReplace) {
					list.value.push(...data)
				} else {
					const preList = list.value.slice(0, (query.value.current - 1) * query.value.size)
					list.value = preList.concat(data)
				}
				let curLength = list.value.length || 0
				loadStatus.value = curLength === total.value? 'nomore' : 'loadmore'
			}).catch(() => {
				query.value.current --
				loadStatus.value = 'loadmore'
			})
		}
	}
	function restore() {
		triggered.value = false
	}
	function goArrange(id) {
		arrangeForm.value.shippingId = id
		arrangePopup.value.open()
	}
	function arrangeSubmit() {
		arrangeUForm.value.validate().then(() => {
			loading.value = true
			arrangeTask(arrangeForm.value.shippingId, arrangeForm.value.deliveryCode).then(res => {
				uni.showToast({icon: 'success', title: '整理成功'})
				setTimeout(() => {
					triggered.value = true
				}, 200)
				arrangePopup.value.close()
				loading.value = false
			}).catch(() => loading.value = false)
		})
	}
	function arrangeChange(e) {
		if(!e.show) {
			arrangeUForm.value.resetFields()
		}
	}
	function goDelivery() {
		if(selectStartList.value.length) {
			startTask(selectStartList.value).then(res => {
				uni.showToast({icon: 'success', title: '确认成功'})
				setTimeout(() => {
					triggered.value = true
				}, 200)
				selectStartList.value = []
			})
		} else {
			uni.showToast({icon: 'none', title: '请选择配送任务'})
		}
	}
	function goArrive() {
		if(selectConfirmList.value) {
			form.value.shippingId = selectConfirmList.value
			arrivePopup.value.open()
		} else {
			uni.showToast({icon: 'none', title: '请选择配送任务'})
		}
	}
	function submit() {
		uForm.value.validate().then(() => {
			loading.value = true
			confirmTask(form.value).then(res => {
				uni.showToast({icon: 'success', title: '确认成功'})
				setTimeout(() => {
					triggered.value = true
				}, 200)
				arrivePopup.value.close()
				loading.value = false
				selectConfirmList.value = ''
			}).catch(() => loading.value = false)
		})
	}
	function arriveChange(e) {
		if(!e.show) {
			uForm.value.resetFields()
		}
	}
	function chooseImg() {
		let typeList = ['png', 'jpg']
		uni.chooseImage({ 
			count: Math.abs(4 - Number(form.value.list.length)),
			sourceType: ['album', 'camera'], // 可以选择相册或相机
			success: async res => {
				let list = res.tempFiles
				let errType = list.some(file => !typeList.includes(getFileType(file.path)))
				if (errType) {
					uni.showToast({icon: 'none', title: '请上传图片格式为png/jpg'})
					return
				}
				let moreSize = list.some(file => file.size > 5242880)
				if (moreSize) {
					uni.showToast({icon: 'none', title: '上传图片大小不能超过5M'})
					return
				}
				loading.value = true
				for (let i = 0; i < list.length; i++) {
					try {
						const result = await uploadFile({filename: '送达图片', filePath: list[i].path})
						form.value.list.push(result.result)
					} catch (e) {}
				}
				uForm.value.validateField('list')
				loading.value = false
			}
		})
	}
	function removeImg(index){
		form.value.list.splice(index, 1)
		uForm.value.validateField('list')
	}
	function viewImg(index) {
		let urls = form.value.list.map(item => item.furl)
		uni.previewImage({
			current: index,
			urls: urls
		})
	}
	function contact(phone) {
		uni.makePhoneCall({
			phoneNumber: phone
		})
	}
	function goView(id, index) {
		let url = `/delivery/pages/taskDetail?id=${id}&index=${index}`
		uni.navigateTo({url})
	}
	function changeExpand(item) {
		item.expand = !item.expand
	}
	
	onLoad(() => {
		triggered.value = true
	})
</script>

<template>
	<view class="app-container">
		<view class="app-head">
			<uv-tabs :list="navList" :current="query.status" :activeStyle="{color: '#1A1816', fontWeight: 'bold'}" :inactiveStyle="{color: '#606060'}"  @change="navChange" lineWidth="60" :lineHeight="6" lineColor="#FF3E49" :scrollable="false" :disabled="loadStatus === 'loading'"></uv-tabs>
		</view>
		<scroll-view scroll-y="true" :class="['app-content', [1,2].includes(query.status)? 'show-bottom' : '']" refresher-enabled :refresher-triggered="triggered" @refresherrefresh="refreshList" lower-threshold="10" @scrolltolower="lowerList" @refresherrestore="restore">
			<view class="content-list" v-if="list.length">
				<template v-if="query.status === 0">
					<view class="list-box" v-for="(item, index) in list" :key="item.shippingId">
						<view class="content-top">
							<view class="top-right">
								<view class="top-time">用户期望送达时间：{{parseTime(item.expectedTime, '{m}月{d}日')}}</view>
								<view class="top-index">{{index}}</view>
							</view>
						</view>
						<view class="content-center">
							<view class="address-box">
								<uv-icon name="map-fill" color="#FC4C11" size="72" />
								<view class="address-info">
									<view class="info-city">{{item.receiverDetailAddress}}</view>
									<view class="info-detail">{{item.receiverAddress}}</view>
								</view>
							</view>
							<view class="center-num">商品共计：{{item.quantity}}件</view>
							<view class="center-no">订单号：{{item.code}}</view>
						</view>
						<view class="center-bottom flex-end">
							<uv-button color="#606060" shape="circle" text="查看详情" @click="goView(item.shippingId, index)" :plain="true"></uv-button>
							<uv-button color="#FF3E49" shape="circle" text="整理完成" @click="goArrange(item.orderId)"></uv-button>
						</view>
					</view>
				</template>
				<uv-checkbox-group v-model="selectStartList" placement="column" shape="circle" size="32" iconSize="32" activeColor="#FA3F00" v-if="query.status === 1">
					<view class="list-box" v-for="(item, index) in list" :key="item.shippingId">
						<view class="content-top">
							<uv-checkbox :name="item.shippingId">
								<view class="top-right">
									<view class="top-time">用户期望送达时间：{{parseTime(item.expectedTime, '{m}月{d}日')}}</view>
									<view class="top-index">{{index}}</view>
								</view>
							</uv-checkbox>
						</view>
						<view class="content-center">
							<view class="address-box">
								<uv-icon name="map-fill" color="#FC4C11" size="72" />
								<view class="address-info">
									<view class="info-city">{{item.receiverDetailAddress}}</view>
									<view class="info-detail">{{item.receiverAddress}}</view>
								</view>
							</view>
							<view class="center-num">商品共计：{{item.quantity}}件</view>
							<view class="center-no">订单号：{{item.code}}</view>
						</view>
						<view class="center-bottom">
							<view class="bottom-contact" @click="contact(item.receiverPhone)">
								<uv-icon name="phone-fill" color="#606060" size="40" /><text>联系</text>
							</view>
							<view class="bottom-btn">
								<uv-button color="#606060" shape="circle" text="查看详情" @click="goView(item.shippingId, index)" :plain="true"></uv-button>
							</view>
						</view>
					</view>
				</uv-checkbox-group>
				<uv-radio-group v-model="selectConfirmList" placement="column" size="32" iconSize="32"activeColor="#FA3F00" v-if="query.status === 2">
					<view class="list-box" v-for="(item, index) in list" :key="item.shippingId">
						<view class="content-top">
							<uv-radio :name="item.shippingId">
								<view class="top-right">
									<view class="top-time">用户期望送达时间：{{parseTime(item.expectedTime, '{m}月{d}日')}}</view>
									<view class="top-index">{{index}}</view>
								</view>
							</uv-radio>
						</view>
						<view class="content-center">
							<view class="address-box">
								<uv-icon name="map-fill" color="#FC4C11" size="72" />
								<view class="address-info">
									<view class="info-city">{{item.receiverDetailAddress}}</view>
									<view class="info-detail">{{item.receiverAddress}}</view>
								</view>
							</view>
							<view class="center-num">商品共计：{{item.quantity}}件</view>
							<view class="center-no">订单号：{{item.code}}</view>
						</view>
						<view class="center-bottom">
							<view class="bottom-contact" @click="contact(item.receiverPhone)">
								<uv-icon name="phone-fill" color="#606060" size="40" /><text>联系</text>
							</view>
							<view class="bottom-btn">
								<uv-button color="#606060" shape="circle" text="查看详情" @click="goView(item.shippingId, index)" :plain="true"></uv-button>
							</view>
						</view>
					</view>
				</uv-radio-group>
				<template v-if="query.status === 3">
					<view class="list-box" v-for="(item, index) in list" :key="item.shippingId">
						<view class="content-top">
							<view class="top-right">
								<view class="top-time">用户期望送达时间：{{parseTime(item.expectedTime, '{m}月{d}日')}}</view>
								<view class="top-index">{{index}}</view>
							</view>
						</view>
						<view class="content-center">
							<view class="address-box">
								<uv-icon name="map-fill" color="#FC4C11" size="72" />
								<view class="address-info">
									<view class="info-city">{{item.receiverDetailAddress}}</view>
									<view class="info-detail">{{item.receiverAddress}}</view>
								</view>
							</view>
							<view class="center-num">商品共计：{{item.quantity}}件</view>
							<view class="center-no">订单号：{{item.code}}</view>
						</view>
						<view class="center-bottom">
							<view class="bottom-contact">
								<uv-icon name="checkmark-circle-fill" color="#10B02D" size="40" /><text>完成</text>
							</view>
							<view class="bottom-btn">
								<uv-button color="#606060" shape="circle" text="查看详情" @click="goView(item.shippingId, index)" :plain="true"></uv-button>
							</view>
						</view>
					</view>
				</template>
				<uv-load-more :status="loadStatus" fontSize="28" iconSize="34" isDot line></uv-load-more>
			</view>
			<empty :text="'没有找到' + navList[query.status].name + '任务'" v-else></empty>
		</scroll-view>
		<view class="app-bottom" v-if="[1,2].includes(query.status)">
			<uv-button color="linear-gradient( 102deg, #FA3F00 0%, #FF7445 100%)" shape="circle" text="开始配送" @click="goDelivery" v-if="query.status === 1"
				:disabled="loading"></uv-button>
			<uv-button color="linear-gradient( 102deg, #FA3F00 0%, #FF7445 100%)" shape="circle" text="确认送达" @click="goArrive" v-else-if="query.status === 2"
				:disabled="loading"></uv-button>
		</view>
		
		<uv-popup ref="arrangePopup" closeable mode="center" bgColor="none" @change="arrangeChange">
			<view class="popup-box">
				<view class="popup-title">提货验证码</view>
				<view class="popup-content">
					<uv-form :model="arrangeForm" :rules="arrangeRules" ref="arrangeUForm" labelWidth="auto" labelPosition="top">
						<uv-form-item prop="deliveryCode">
							<view class="code-box">
								<uv-code-input v-model="arrangeForm.deliveryCode" :maxlength="4" :space="48" color="#202020" size="112" fontSize="56"></uv-code-input>
							</view>
						</uv-form-item>
					</uv-form>
				</view>
				<view class="popup-bottom">
					<uv-button color="linear-gradient(102deg, #FA3F00 0%, #FF7445 100%)" shape="circle" text="提 交" @click="arrangeSubmit" :disabled="loading">
					</uv-button>
				</view>
			</view>
		</uv-popup>
		<uv-popup ref="arrivePopup" closeable mode="center" bgColor="none" @change="arriveChange">
			<view class="popup-box">
				<view class="popup-title">司机拍照上传送达图片</view>
				<view class="popup-content">
					<uv-form :model="form" :rules="rules" ref="uForm" labelWidth="auto" labelPosition="top">
						<uv-form-item label="上传送达图片（最多4张）" prop="list">
							<view class="image-box">
								<view class="image-item" v-for="(img, index) in form.list" :key="index">
									<uv-image :src="img && img.furl" width="144" height="144" @click="viewImg(index)"></uv-image>
									<view class="image-del" @click.stop="removeImg(index)">
										<uv-icon name="close" color="#FFFFFF" size="30" />
									</view>
								</view>
								<view class="image-item select" @click="chooseImg" v-if="form.list.length < 4">
									<uv-icon name="plus" color="#767473" size="30" bold />
								</view>
							</view>
						</uv-form-item>
						<uv-form-item label="用户验证码" prop="deliveryCode">
							<view class="code-box">
								<uv-code-input v-model="form.deliveryCode" :maxlength="4" :space="48" color="#202020" size="112" fontSize="56"></uv-code-input>
							</view>
						</uv-form-item>
					</uv-form>
				</view>
				<view class="popup-bottom">
					<uv-button color="linear-gradient(102deg, #FA3F00 0%, #FF7445 100%)" shape="circle" text="提 交" @click="submit" :disabled="loading"></uv-button>
				</view>
			</view>
		</uv-popup>
	</view>
</template>

<style lang="scss" scoped>
	.app-container{
		height: 100vh;
		padding-top: 2rpx;
		.app-head{
			background-color: #FFFFFF;
		}
		.app-content{
			width: 100%;
			height: calc(100% - 88rpx);
			&.show-bottom{
				height: calc(100% - 200rpx);
			}
			.content-list{
				padding: 24rpx 24rpx 0;
				.list-box{
					padding: 24rpx;
					margin-bottom: 24rpx;
					background-color: #FFFFFF;
					border-radius: 16rpx;
				}
				.list-box:last-child{
					margin-bottom: 0;
				}
			}
		}
		.content-top{
			padding-bottom: 24rpx;
			border-bottom: 2rpx solid #F4F4F4;
			.top-right{
				display: flex;
				align-items: center;
				gap: 8rpx;
				.top-time{
					flex: 1;
					color: #606060;
				}
				.top-index{
					flex-shrink: 0;
					width: 56rpx;
					height: 56rpx;
					line-height: 56rpx;
					text-align: center;
					font-weight: 600;
					color: #FC4C11;
					background-color: #FFCCB6;
					border-radius: 28rpx;
				}
			}
		}
		.content-center{
			padding: 24rpx 0;
			border-bottom: 2rpx solid #F4F4F4;
			.address-box{
				display: flex;
				align-items: center;
				gap: 10rpx;
				.address-info{
					width: calc(100% - 82rpx);
					.info-city{
						font-weight: 600;
						font-size: var(--theme-lg);
						line-height: var(--theme-lg-line);
					}
					.info-detail{
						margin-top: 8rpx;
						color: #1A1816;
					}
				}
			}
			.center-num{
				margin-top: 24rpx;
				color: #606060;
			}
			.center-no{
				margin-top: 16rpx;
				color: #606060;
			}
		}
		.center-bottom{
			padding-top: 24rpx;
			display: flex;
			align-items: center;
			gap: 16rpx;
			.bottom-contact{
				display: flex;
				flex-direction: column;
				align-items: center;
				gap: 4rpx;
				color: #1A1816;
			}
			.bottom-btn{
				flex: 1;
			}
			&.flex-end{
				justify-content: flex-end;
			}
		}
		.app-bottom{
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0rpx;
			z-index: 10;
			height: 112rpx;
			padding: 16rpx 24rpx;
			background-color: #FFFFFF;
			border-top: 2rpx solid #D7DBE1;
		}
		.popup-box{
			width: 686rpx;
			background: linear-gradient( 180deg, #F9E7E7 0%, #FFFFFF 24%);
			border-radius: 32rpx;
			padding: 32rpx;
			.popup-title{
				padding-bottom: 24rpx;
				font-weight: 600;
				font-size: var(--theme-lg);
				line-height: var(--theme-lg-line);
			}
			.popup-content{
				.image-box{
					margin-top: 14rpx;
					width: 100%;
					display: flex;
					gap: 16rpx;
					.image-item{
						width: 144rpx;
						height: 144rpx;
						border-radius: 8rpx;
						background-color: #F8F5F5;
						position: relative;
						.image-del{
							position: absolute;
							top: 0;
							right: 0;
							width: 36rpx;
							height: 36rpx;
							background-color: rgba(28,33,62,0.5);
							border-top-right-radius: 8rpx;
							display: flex;
							justify-content: center;
							align-items: center;
						}
						&.select{
							display: flex;
							justify-content: center;
							align-items: center;
						}
					}
				}
				.code-box{
					margin-top: 14rpx;
					display: flex;
					justify-content: center;
				}
				::v-deep .uv-form-item__body {
					padding: 0 0 24rpx;
				}
				::v-deep .uv-code-input__item{
					border: 0 !important;
					background-color: rgba(32,32,32,0.04);
					border-radius: 20rpx;
				}
			}
			.popup-bottom{
				padding-top: 32rpx;
			}
		}
	}
</style>